//
//  ScrollviewBanner.m
//  Kugou-OC
//
//  Created by BH on 16/5/30.
//  Copyright © 2016年 Sunny. All rights reserved.
//

#import "ScrollviewBanner.h"
#import "GlobalDefine.h"
#import "TapImageView.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <SDAutoLayout/UIView+SDAutoLayout.h>

@interface ScrollviewBanner ()<UIScrollViewDelegate>

//UIImage 数组
@property(nonatomic,strong)NSMutableArray *imagesArray;
@property(nonatomic,strong)UIScrollView *scrollview;
@property(nonatomic,strong)UIPageControl *pageCtrl;

@end

@implementation ScrollviewBanner

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        
        _imagesArray = [NSMutableArray array];
        
        [self setScrollView];
    }
    
    return self;
}

-(void)setPageHidden:(BOOL)pageHidden{
    _pageHidden = pageHidden;
    
    if (pageHidden) {
        self.pageCtrl.hidden = YES;
    }else{
        self.pageCtrl.hidden = NO;
    }
}

-(void)setItems:(NSArray *)items{
    _items = items;
    
    NSMutableArray *tempArr = [NSMutableArray array];
    if (_itemsSource == kBannerSourceTypeLocal) {
        
        for (int i = 0; i<_items.count; i++) {
            UIImage *image = IMAGE(_items[i]);
            [tempArr addObject:image];
        }
        
        _imagesArray = [NSMutableArray arrayWithArray:tempArr];
        [_imagesArray insertObject:tempArr.lastObject atIndex:0];
        
        //本地
        [self addItemsWithLocal];
        
    }else{
        
        //网络
        [self addItemsWithNetAndHorizon];
    }
    
    //添加pagecontrol
    [self setPageControl];
    //定时轮播
    [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(autoPlay) userInfo:nil repeats:YES];
}

//来自本地
-(void)addItemsWithLocal{
    TapImageView *imageView=nil;
    
    for (int i=0; i<_imagesArray.count; i++) {
        TapImageView *imgV = [[TapImageView alloc] init];
        imgV.backgroundColor = [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1];
        imgV.tag = 200+i;
        [_scrollview addSubview:imgV];
        
        imgV.Taphandle = ^(UIView *view){
            NSLog(@"%d",(short)view.tag);
        };
        
        if (imageView) {
            imgV.image = _imagesArray[i];
            imgV.sd_layout.leftSpaceToView(imageView,0).topEqualToView(imageView).widthIs(SCREEN_WIDTH).bottomEqualToView(imageView);
        }else{
            imgV.image = _imagesArray[i+1];
            imgV.sd_layout.leftSpaceToView(_scrollview,0).topSpaceToView(_scrollview,0).rightSpaceToView(_scrollview,0).bottomSpaceToView(_scrollview,0);
        }
        
        imageView = imgV;
    }
    
    [_scrollview setupAutoContentSizeWithRightView:imageView rightMargin:0];
}

/**
 *  来自网络
 */
-(void)addItemsWithNetAndHorizon{
    
    TapImageView *imageView=nil;
    
    for (int i=0; i<_items.count; i++) {
        TapImageView *imgV = [[TapImageView alloc] init];
        imgV.tag = 200+i;
        [_scrollview addSubview:imgV];
        
        imgV.Taphandle = ^(UIView *view){
            NSLog(@"%d",(short)view.tag);
        };
        
        [imgV sd_setImageWithURL:[NSURL URLWithString:_items[i]] placeholderImage:IMAGE(@"placeholder_rectangle") completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            [_imagesArray addObject:imgV.image];
            if (i==_items.count-1) {
                [_imagesArray insertObject:imgV.image atIndex:0];
            }
        }];
        
        if (imageView) {
            imgV.sd_layout.leftSpaceToView(imageView,0).topEqualToView(imageView).widthIs(SCREEN_WIDTH).bottomEqualToView(imageView);
        }else{
            imgV.sd_layout.leftSpaceToView(_scrollview,0).topSpaceToView(_scrollview,0).widthIs(SCREEN_WIDTH).bottomSpaceToView(_scrollview,0);
        }
        
        imageView = imgV;
    }
    
    [_scrollview setupAutoContentSizeWithRightView:imageView rightMargin:0];
}

-(void)setScrollView{
    _scrollview = ALLOC(UIScrollView);
    _scrollview.delegate = self;
    _scrollview.pagingEnabled = YES;
    _scrollview.showsHorizontalScrollIndicator = NO;
    _scrollview.showsVerticalScrollIndicator = NO;
    [self addSubview:_scrollview];
    
    _scrollview.sd_layout.leftSpaceToView(self,0).topSpaceToView(self,0).rightSpaceToView(self,0).bottomSpaceToView(self,0);
}

-(void)setPageControl{
    _pageCtrl = [[UIPageControl alloc] init];
    _pageCtrl.numberOfPages = _items.count;
    _pageCtrl.currentPage = 0;
    _pageCtrl.hidden = NO;
    _pageCtrl.pageIndicatorTintColor = [UIColor whiteColor];
    _pageCtrl.currentPageIndicatorTintColor = BG_COLOR;
    [_pageCtrl addTarget:self action:@selector(pageValueChange:) forControlEvents:UIControlEventValueChanged];
    [self addSubview:_pageCtrl];
    _pageCtrl.sd_layout.centerXEqualToView(self).bottomSpaceToView(self,20).widthIs(1*_items.count).heightIs(10);
}

-(void)pageValueChange:(UIPageControl *)pageControl{
    NSInteger page = pageControl.currentPage;
    CGFloat x = (page + 1) * self.width;
    [_scrollview setContentOffset:(CGPointMake(x, 0)) animated:YES];
}

//自动轮播
-(void)autoPlay{
    CGFloat x = _scrollview.contentOffset.x;//获取偏移量
    if (x + self.width >= _scrollview.contentSize.width) {//判断增加后的偏移量是否超过范围
        [_scrollview setContentOffset:(CGPointMake(0, 0)) animated:NO];//先把偏移量置为（0，0）
        _pageCtrl.currentPage = 0;

    }else {
        [_scrollview setContentOffset:(CGPointMake(x + self.width, 0)) animated:YES];
    }
}

#pragma mark - UIScrollview delegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat x = scrollView.contentOffset.x;
    if (x > (self.imagesArray.count - 1) * self.width) {//最后一张图 再次滑动 重置 把偏移量置为（0，0）
        [_scrollview setContentOffset:(CGPointMake(0, 0)) animated:NO];//重置scrollView偏移量
    }
    if (x < 0) {//当为第一张图时 再滑动把偏移量置为最后一张图
        [_scrollview setContentOffset:(CGPointMake((self.imagesArray.count - 1) *self.width, 0)) animated:NO];
    }
}

// 滚动动画结束的时候更改pageControl
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    CGFloat x = scrollView.contentOffset.x;//获取当前的偏移量
    NSInteger page = x / self.width - 1;//对应的pageControl值
    //如果page小于0 说明是衔接图 pageControl下标为最后
    if (page < 0) {
        _pageCtrl.currentPage = self.imagesArray.count - 1;
    }else {
        _pageCtrl.currentPage = page+1;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGFloat x = scrollView.contentOffset.x;//获取当前的偏移量
    NSInteger page = x / self.width - 1;//对应的pageControl值
    //如果page小于0 ，说明是衔接图，pageControl下标为最后
    if (page < 0) {
        _pageCtrl.currentPage = self.imagesArray.count - 1;
    }else {
        _pageCtrl.currentPage = page+1;
    }
}

@end
